﻿var swfu;
$(document).ready(function() {
    var settings = {
        // Backend Settings
        upload_url: _URL_UPLOAD_URL,
        post_params: {
        "ASPSESSID": _ASPNETSESSIONID,
        "AUTHID": _AUTHID
        },
        // File Upload Settings
        file_size_limit: _MaxSingleFileSize,
        file_types: _AllowTypes,
        file_types_description: "图片文件",
        file_upload_limit: "10",
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogComplete,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccess,
        upload_complete_handler: uploadComplete,
        file_queued_handler: fileQueued,

        // Button settings
        button_image_url: _UploadButtonBG,
        button_placeholder_id: "spanButtonPlaceholder",
        button_width: 75,
        button_height: 22,
        button_text: '<span class="button">选择照片</span>',
        button_text_style: '.button {color:#0000cc; text-align:center;}',
        button_text_top_padding: 1,
        button_text_left_padding: 1,


        // Flash Settings
        flash_url: _SWFUploadFlashUrl,

        custom_settings: {
            upload_target: "divFileProgressContainer"
        },

        // Debug Settings
        debug: false
    };
    swfu = new SWFUpload(settings);
});

function fileQueued(file) {
    queueFile(file);
}
var total_size = 0;
var total_count = 0;
function queueFile(file) {
    var strSelectFileHTML = '';

    strSelectFileHTML += '<div title="' + file.name + '" id="select_file_' + file.index + '" style="clear:all;color:#000000;height:30px;border-bottom:1px solid #CCCCCC;">';

    strSelectFileHTML += '<div style="padding-top:8px">';
    strSelectFileHTML += '<div style="float:left;width:241px;"><div style="width:231px;overflow:hidden;padding-left:5px">' + file.name + '</div></div>';
    strSelectFileHTML += '<div style="float:left;width:70px"><div style="width:65px;padding-left:5px">' + getFileSize(file.size) + '</div></div>';
    strSelectFileHTML += '<div style="float:left;width:70px"><div id="remove_file_' + file.index + '" style="width:65px;padding-left:5px"><a name="remove_one_file" title="移除：' + file.name + '" class="grayLink" href="javascript:void 0;" onclick="javascript:removefile(' + file.index + ',\'' + file.id + '\');return false;" style="text-decoration:none;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div></div>';
    strSelectFileHTML += '</div>';

    strSelectFileHTML += '</div>';
    strSelectFileHTML += '<div id="progress_bar_' + file.index + '" style="background-color:#F7F7F7; width:0px; FILTER: alpha(opacity=70); height:28px; margin-top:-30px; z-index:100;" >';
    strSelectFileHTML += '</div>';
    document.getElementById('select_file_container').innerHTML += strSelectFileHTML;
    total_size += file.size;
    total_count++;
    updateFileInfo();
}


function updateFileInfo() {
    document.getElementById('totalselectcount').innerHTML = total_count;
    document.getElementById('totalselectsize').innerHTML = getFileSize(total_size);
}

function getFileSize(fileSizeByte) {
    fileSizeByte = parseInt(fileSizeByte);
    var fileSize = '';
    if (fileSizeByte == 0) {
        return '0KB';
    } else if (fileSizeByte <= 1024) {
        return getFloadString(fileSizeByte) + 'B';
    } else if (fileSizeByte <= 1024 * 1024) {
        return getFloadString(fileSizeByte / 1024) + 'KB';
    } else {
        return getFloadString(fileSizeByte / (1024 * 1024)) + 'MB';
    }
}

function getFloadString(numString) {
    numString = numString + '';
    var dotFlag = numString.indexOf('.');
    if (dotFlag > -1) {
        numString = numString.substring(0, dotFlag + 2);
    } else {
        numString = numString + '.0';
    }
    return numString;
}

function removefile(fileIndex, fileId) {
    var delete_file = document.getElementById('select_file_' + fileIndex);
    delete_file.parentNode.removeChild(delete_file);
    var file = swfu.getFile(fileIndex);
    if (file) {
        total_count--;
        total_size -= file.size;
        updateFileInfo();
    }

    swfu.cancelUpload(fileId, false);

}
function createAlbum(title, privacy) {
    $.post(_URL_CREATEALBUM,
           { albumtitle: title, privacy: privacy },
           function(ret) {
               if (ret > 0) {
                   swfu.addPostParam('albumId', ret);
                   doupload();
               }
               else
                   alert(ret);
           }
           );
}

function upload() {
    try {
        if (swfu && swfu.getStats().files_queued > 0) {


            var album_list = $("#albumList");
            var albumId = -1;
            if (album_list.val() == '0') {//新建
                var newAlbumTitle = $("#tbalbum").val();
                if (newAlbumTitle) {
                    var privacy = $("#album_privacy").val();

                    createAlbum(newAlbumTitle, privacy);
                    //after create album callback,do real upload
                }
                else {
                    alert('请先选择一个相册或填写要新建的相册标题');
                    return;
                }
            }
            else {
                swfu.addPostParam('albumId', album_list.val());
                doupload();
            }

        }
        else
            alert('请先选择要上传的文件');
    } catch (ex) {
        alert(ex);
    }
}
//real upload
function doupload() {
    $('#buttonregion').hide();
    $('#loading').fadeIn();
    swfu.setButtonDisabled(true);
    $('#button_clear_file').attr('disabled', 'disabled');
    $("a[name=remove_one_file]").hide();

    swfu.addPostParam('tags', $('#tbtags').val());
    swfu.startUpload();
}
function clearFiles() {
    document.getElementById('select_file_container').innerHTML = "";
    total_size = 0;
    total_count = 0;
    updateFileInfo();
    var n = 0;
    if (swfu) {
        n = swfu.getStats().files_queued;
        for (i = 0; i < n; i++)
            swfu.cancelUpload(null, false);
    }

}
function fileQueueError(file, errorCode, message) {
	try {		
		var errorName = "";
		switch (errorCode) {
		    case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
		        errorName = "您一次上传的文件数不能超过" + message;
		        break;
		    case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		        errorName = "不能上传空文件";
		        break;
		    case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
		        errorName = "您要上传的文件超过限定大小";
		        break;
		    case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		        errorName = "不能上传这种类型的文件";
		        break;
		    default:
		        alert(message);
		        break;
		}
        alert(errorName);
	} catch (ex) {
		this.debug(ex);
	}

}

function fileDialogComplete(numFilesSelected, numFilesQueued) {	
		if (numFilesQueued > 0) {
		    $('#btnUpload').attr('disabled', '');
		}
	
}

function uploadProgress(file, bytesLoaded) {

    var p = document.getElementById('progress_bar_' + file.index);

	//try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		p.style.width = percent + '%';
		p.style.borderRight = "3px solid #0f0";
		p.style.borderBottom = "3px solid #0f0";
}

function uploadSuccess(file, serverData) {
	try {
	    if (serverData!="false") {
	        var r = $('#upload-result').val();
	        if (r != "")
	            r += ",";
	        $('#upload-result').val(r + serverData)
	    }
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {    
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
	    if (this.getStats().files_queued > 0) {
	        this.startUpload();
	    }
	    else {
	        //all files uploaded
	        //redirect
	        var ids = $('#upload-result').val();
	        if (ids != "")
	            window.location.href = _URL_PHOTOS_EDIT.replace('0', ids);
	        else {
	            $('#loading').html('上传图片出错，请刷新本页后重试');
	            $('#loading').addClass('error');
	            $('#loading').attr("style", "color:#f00");
	            $('#loading').fadeIn();
	        }
	    }
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	var imageName =  "error.gif";
	var progress;
	try {
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			imageName = "uploadlimit.gif";
			break;
		default:
			alert(message);
			break;
		}

		addImage("images/" + imageName);

	} catch (ex3) {
		this.debug(ex3);
	}

}


function addImage(src) {
	var newImg = document.createElement("img");
	newImg.style.margin = "5px";

	document.getElementById("thumbnails").appendChild(newImg);
	if (newImg.filters) {
		try {
			newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		newImg.style.opacity = 0;
	}

	newImg.onload = function () {
		fadeIn(newImg, 0);
	};
	newImg.src = src;
}

function fadeIn(element, opacity) {
	var reduceOpacityBy = 5;
	var rate = 30;	// 15 fps


	if (opacity < 100) {
		opacity += reduceOpacityBy;
		if (opacity > 100) {
			opacity = 100;
		}

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (opacity < 100) {
		setTimeout(function () {
			fadeIn(element, opacity);
		}, rate);
	}
}


